package com.zlp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;



@Controller
public class LoginController {
	
    /**
     * 登录请求
     * @param request
     * @param username
     * @param password
     * @return
     */
	@RequestMapping("/loginUser")
	@ResponseBody
    public String loginUser(HttpServletRequest request,String username,String password) {
        //授权认证
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            //完成登录
            subject.login(usernamePasswordToken);
            return "index";
        } catch(Exception e) {
            return "login";//返回登录页面
        }
    }
	
	//配合shiro配置中的默认访问url
	@GetMapping(value="/login")
	public String getLogin(HttpServletRequest request,HttpServletResponse response){
		return "login";
	}
		
		
		@RequestMapping(value="/",method=RequestMethod.GET)
		public String index(){
			System.out.println("访问了后端 /  请求");
			return "login";
		}
		
		/**
		* 退出
		 * @return
		 */
		@RequestMapping(value="/logout",method =RequestMethod.GET)
		public String logout(HttpServletRequest request){
			//subject的实现类DelegatingSubject的logout方法，将本subject对象的session清空了
			//即使session托管给了redis ，redis有很多个浏览器的session
			//只要调用退出方法，此subject的、此浏览器的session就没了
			try {
				//退出
				SecurityUtils.getSubject().logout();
			} catch (Exception e) {
				System.err.println(e.getMessage());
			}
			return "login";
		}
		
		@RequestMapping(value="403",method=RequestMethod.GET)
		public String unAuth(){
			
			return "403";
			
		}

	
}
